package Network.homework;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket=null;
    private String serverIP;
    private int serverPort;
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        socket=new DatagramSocket();
        this.serverIP=serverIP;
        this.serverPort=serverPort;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scan=new Scanner(System.in);
        while(true){
            System.out.print("->");
            //1.用户输入请求
            if(!scan.hasNext()){
                break;//请求输入结束
            }
            String request=scan.next();
            //2.将请求发送到服务器
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length,
                                                InetAddress.getByName(serverIP),serverPort);
            socket.send(requestPacket);
            //3.接收服务器的响应
            DatagramPacket responsePacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            String response=new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }

    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1", 9090);
        udpEchoClient.start();
    }
}
